//
//  YFTitleButton.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/9/5.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

class YFTitleButton: UIButton {

    init(title: String?) {
        super.init(frame: CGRect())
        ///< 判断是否有title
        if title == nil {
            setTitle("首页", for: .normal)
        }else {
            setTitle(title! + " ", for: .normal)
            setImage(#imageLiteral(resourceName: "arrow_down"), for: .normal)
            setImage(#imageLiteral(resourceName: "arrow_up"), for: .selected)
        }
        ///< 设置字体属性
        setTitleColor(.darkGray, for: .normal)
        ///< 将字体改成粗体
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        guard let imageView = imageView,
            let titleLabel = titleLabel else {
                return
        }
        titleLabel.hm_x = titleLabel.hm_x - imageView.hm_width
        imageView.hm_x = imageView.hm_x + titleLabel.hm_width
        ///< 设置大小(自适应大小)
        sizeToFit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



extension YFTitleButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        guard let imageView = imageView,
            let titleLabel = titleLabel else {
                return
        }
//        titleLabel.hm_x = titleLabel.hm_x - imageView.hm_width
//        imageView.hm_x = imageView.hm_x + titleLabel.hm_width
        /**
         * 将label的x向左移动imageView的宽度
         * OC中不允许直接修改'结构体'内部的值
         * Swift中可以直接修改
         */
        titleLabel.frame.origin.x = 0
        imageView.frame.origin.x = titleLabel.bounds.width
    }
}
